// pages/chat/chat.ts
import { getGuideList } from '../../api/guide';
import { createQuestion, getMyQuestionList, ModifyQuestion } from '../../api/question';
import { debounce } from '../../utils/debounce'
import { isLogin, login } from '../../utils/login';

Page({
  /**
   * 页面的初始数据
   */
  data: <any>{
    active: 1,
    showJoinWebinarDialog: false,
    editorValue: '',
    formInfo: {
      userId: '',
      title: '',
      content: ''
    },
    modelId: '',
    list: [], // 问答列表
    guideList: []
  },

  onShow(){
    this.getGuideListHandle()
  },

  // 标题输入事件
  onTitleInput(e: any) {
    const { index } = e.currentTarget.dataset;
    const title = e.detail.value;
    const list = this.data.list;
    list[index].title = title;
    this.setData({
      list
    });
  },

  // 内容输入事件
  onContentInput(e: any) {
    const { index } = e.currentTarget.dataset;
    const content = e.detail.value;
    const list = this.data.list;
    list[index].content = content;
    this.setData({
      list
    });
  },

  // 切换编辑状态
  toggleEdit(e: any) {
    const { index } = e.currentTarget.dataset;
    const list = this.data.list;
    const item = list[index];

    if (item.editing) {
      // 如果当前是编辑状态，点击取消，恢复原始数据
      item.title = item.originalTitle;
      item.content = item.originalContent;
      item.editing = false;
    } else {
      // 如果当前是查看状态，点击编辑，保存原始数据
      item.originalTitle = item.title;
      item.originalContent = item.content;
      item.editing = true;
    }

    this.setData({
      list
    });
  },

  onSelectChange(e: any){
    const data = e.detail.selectData
    this.setData({
      modelId: data.id
    })
  },

  getGuideListHandle(){
    getGuideList({
      pageNum: 1,
      pageSize: 300
    }).then(res => {
      if(res.rows && res.rows.length > 0){
        this.setData({
          guideList: res.rows.map(item => ({ ...item, text: item.name }))
        })
        getApp().globalData.guideList = res.rows
      }else{
        this.setData({
          searchGuideList: [],
          guideList: []
        })
      }
    })
  },

  // 保存编辑内容
  saveEdit(e: any) {
    const { index } = e.currentTarget.dataset;
    const list = this.data.list;
    const item = list[index];
    item.editing = false;
    this.setData({
      list
    });

    this.updateQuestion(item.id, item.title, item.content);
  },

  // 更新问题的接口
  updateQuestion(questionId: number, title: string, content: string) {
    ModifyQuestion({
      id: questionId,
      title,
      content
    }).then(res => {
      wx.showToast({
        title: '更新成功',
        icon: 'success',
        duration: 2000
      });
    }).catch(err => {
      wx.showToast({
        title: '更新失败',
        icon: 'error',
        duration: 2000
      });
    });
  },

  caseHandle(data: any){
    const { index } = data.currentTarget.dataset
    this.setData({
      active: index
    })
    if(index === '2'){
      this.getQuestionList()
    }
  },

  getQuestionList(){
    getMyQuestionList({
      pageNum: 1,
      pageSize: 500
    }).then(res => {
      if(res && res.rows && res.rows.length > 0){
        this.setData({
          list: res.rows
        })
      }else{
        this.setData({
          list: []
        })
      }
    })
  },

  backToCase(){
    wx.navigateBack({
      delta: 1  // delta 值为 1 时表示关闭当前页面
    });
  },

  editorInputHandle: debounce((e: any, context: any) => {
    const { text } = e.detail;
    context.setData({
      editorValue: text
    })
  }),

  reset(){
    const guideSelector = this.selectComponent("#guideSelector");
    if (guideSelector) {
      guideSelector.resetSelect(); // 调用组件的重置方法
    }
  },

  formSubmit: function(e: any){
    if(isLogin()){
      const userInfo = login()
      if(!userInfo){
        wx.showToast({
          title: '请登录',
          icon: 'none'
        });
        return
      }

      let formData = e.detail.value;
      let isEmpty = false;

      for (let key in formData) {
        if (formData[key] === '') {
          isEmpty = true;
          break;
        }
      }

      if (isEmpty) {
        wx.showToast({
          title: '请补充信息',
          icon: 'none'
        });
        return;
      }

      createQuestion({
        userId: userInfo.id,
        title: formData.title,
        content: formData.content,
        modelId: this.data.modelId
      }).then((res: any) => {
        wx.showToast({
          title: '上传成功',
          icon: 'success',
          duration: 2000,
        })
        this.setData({
          modelId: '',
          'formInfo.title': '',
          'formInfo.content': ''
        });
        this.reset()
      }).catch(e => {
        wx.showToast({
          title: '上传出错',
          icon: 'error',
          duration: 2000,
        })
        console.log(e)
      })
    }
    
  },

  formatAiMessage(message: string){
    const jsonRegex = /```json\s*(\{[\s\S]*\})\s*```/;
    const match = message.match(jsonRegex);

    if (match && match[1]) {
      try {
        const jsonObject = JSON.parse(match[1]);
        return jsonObject;
      } catch (e) {
        console.error('Failed to parse JSON:', e);
        return null;
      }
    } else {
      console.error('No JSON object found in the string.');
      return null;
    }
  },

  uploadFile(filePath: string){
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: 'https://caca.zn-care.com/api/common/upload', // 开发者服务器接口地址
        filePath,
        name: 'file',
        header: {
          Authorization:  `Bearer ${wx.getStorageSync('token')}`
        },
        success: uploadResult => {
          const data = uploadResult.data
          const jsonRes = JSON.parse(data)
          const { url, fileName } = jsonRes
          if(url){
            resolve({
              url, 
              fileName
            })
          }
        },
        fail: uploadError => {
          wx.hideLoading()
          wx.showToast({
            title: '上传出错',
            icon: 'error',
            duration: 2000,
          })
          reject(uploadError);
        }
      });
    })
  },
  editorCtx: <any>null,
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
    }).exec()
  },

  format(e: any) {
    let { name, value } = e.target.dataset
    if (!name) return
    this.editorCtx.format(name, value)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    getApp().globalData.caseUploadFileContent = {}
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    try {
      this.data.requestTask.abort()
    } catch (error) {
      console.log('还没发请求就退出了，正常不会有影响')
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    let chatoption = JSON.stringify({ data: this.data.chatdata[6], voice_type: "BV700_streaming" })
    console.log('分享的数据', chatoption)
    return {
      "title": "",
      "path": `pages/home/home?active=1`,
      "imageUrl": "/static/img/home.jpg"
    }
  }
})